package com.taoge.framework.controller;

import com.taoge.framework.common.BaseToken;
import com.taoge.framework.common.ResponseData;
import com.taoge.framework.constantsEnum.TokenTypeEnum;
import com.taoge.framework.util.ControllerUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public abstract class BaseController<RequestParam extends BaseParam> {

    private final InheritableThreadLocal<BaseRequest> inheritableThreadLocal = new InheritableThreadLocal<BaseRequest>() {
        protected BaseRequest childValue(BaseRequest baseRequest) {
            return baseRequest == null ? null : BaseRequest.builder().build();
        }
    };
    protected final Logger logger = LogManager.getLogger(getClass());

    @ModelAttribute // 会在Controller方法被调用前执行
    public void setReqAndRes(HttpServletRequest req, HttpServletResponse res) {
        BaseRequest baseRequest = BaseRequest.builder()
                .request(req)
                .response(res)
                .session(req.getSession())
                .build();
        inheritableThreadLocal.set(baseRequest);
    }

    protected HttpServletRequest getRequest() {
        return inheritableThreadLocal.get().getRequest();
    }

    protected HttpServletResponse getResponse() {
        return inheritableThreadLocal.get().getResponse();
    }

    protected HttpSession getSession() {
        return inheritableThreadLocal.get().getSession();
    }

    @ResponseBody
    public abstract ResponseData<?> execute(RequestParam param);

    protected String getValueByKey(String key) {
        return ControllerUtil.getValueByKey(key, getRequest());
    }

    protected String getToken(TokenTypeEnum tokenType) {
        return ControllerUtil.getToken(tokenType, getRequest());
    }

    protected Long getUserId(TokenTypeEnum tokenType) {
        return ControllerUtil.getUserId(tokenType, getRequest());
    }

    protected Integer getPageNum() {
        return ControllerUtil.getPageNum(getRequest());
    }

    protected Integer getPageSize() {
        return ControllerUtil.getPageSize(getRequest());
    }

    protected <T extends BaseToken> T getTokenEntity(TokenTypeEnum tokenType) {
        return ControllerUtil.getTokenEntity(tokenType, getRequest());
    }

    protected void setToken(String token, TokenTypeEnum tokenType, String domain) {
        ControllerUtil.setToken(token, tokenType, domain, getResponse());
    }

    protected void cleanToken(TokenTypeEnum tokenType, String domain) {
        ControllerUtil.cleanToken(tokenType, getResponse(), domain);
    }

}
